from peewee import *
from playhouse.pool import PooledMySQLDatabase

db = PooledMySQLDatabase('test',
                         **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'user': 'root',
                            'password': 'root'},
                         max_connections=32,  # 最大连接数量
                         stale_timeout=300,  # 5 分钟
                         )


class UnknownField(object):
    def __init__(self, *_, **__): pass


class BaseModel(Model):
    class Meta:
        database = db


class User(BaseModel):
    age = IntegerField(null=True)
    birthday = DateTimeField(null=True)
    name = CharField(null=True)

    class Meta:
        table_name = 'user'


# 创建或者删除
# 原生
def my_get_or_create(name):
    try:
        with db.atomic():
            return User.create(name=name)
    except IntegrityError:
        # `name` is a unique column, so this name already exists,
        # making it safe to call .get().
        return User.get(User.name == name)


result = my_get_or_create("赵柳儿")
print(result)
# 简化
user, created = User.get_or_create(name="李思思")
print(user, created)
